from django.shortcuts import render , redirect
from django.http import HttpResponse, StreamingHttpResponse
import os
import uuid
from login.models import PersonalDatails,Content,Discuss,Attention
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# Create your views here.
an=0
# ajax请求唯一验证业务处理
def validateunique(request, username):
    # 输出客户端请求数据的值
    print('待验证的用户名称：{0}'.format(username))
    # 判断用户名是否存在
    # 模拟一个用户列表
    usernams = PersonalDatails.objects.all().values_list('number')
    flag=True
    for code in usernams:
    # 判断用户名是否存在
        if username in code:
            flag=False
    return HttpResponse(flag)

def lointo(request):
    number = request.session.get('number', None)
    man=PersonalDatails.objects.get(number=number)
    print('name: {0}'.format(number))
    if not number:
        # 跳转至登录
        return redirect('/login/index/')
    else:
        # 请求转发跳转至home页面
        return render(request, 'fuanbu.html', locals())
def home(request):
    # 获取session的数据
    number = request.session.get('number', None)
    man=PersonalDatails.objects.get(number=number)
    a=man.head

    lstemp=Content.objects.all()
    # 创建分页器类并设置每页显示的数据格式
    paginator = Paginator(lstemp, 3) # 每页显示3条数据
    # 接收客户端传入的页码
    page = request.GET.get('page')
    # 根据用户传入的页码返回响应的页面数据集
    try:
        lstemp = paginator.page(page)
    except EmptyPage: # 首页查看处理
        lstemp = paginator.page(1)
    except PageNotAnInteger:
        lstemp = paginator.page(paginator.num_pages)
    if not number:
        # 跳转至登录
        return redirect('/login/index/')
    else:
        # 请求转发跳转至home页面
        return render(request, 'dengluzp1.html',locals())




#账号密码的存储以及判断
def hello(request):
    if request.POST:
        # 接收客户端请求数据
        number = request.POST.get('number', None)
        code = request.POST.get('code', None)
        neted = request.POST.get('yy', None)
        print(neted)
        print('number:{0} code:{1}'.format(number, code))
        # 处理请求（登录验证）
        number = request.POST.get('number', None)
        man=PersonalDatails.objects.get(number=number)
        if number == number and code == man.code:
            # 设置响应路径
            rep = redirect('/login/ix?page=1')
            # 将登录账号加密后写入Cookie中
            rep.set_signed_cookie('number', number, salt='www.chinasofti.com')
            if neted=='yy':
                rep.set_signed_cookie('code', code, salt='www.chinasofti.com')
            print('登录账号成功加密并写入Cookie……')
            # 登录成功后，将用户账号写入到session中
            request.session['number'] = number
            request.session['code'] = code
            print('登录账号成功写入Session……')
            # 响应客户端
            return rep
        else:
            # 响应客户端
            return render(request, 'index.html', {'message':'账号密码错误'})
    else:
        # 从Cookie中获取number的值
        number = request.get_signed_cookie('number', None, salt='www.chinasofti.com')
        code= request.get_signed_cookie('code', None, salt='www.chinasofti.com')

        
        # 判断accont是否存在，决定是否补填数据
        if number and code:    
            context={"number":number,"code":code}
            return render(request, 'index.html',context)
        elif number:
            return render(request, 'index.html', {'number':number})
        else:
            # 响应客户端（页面跳转）
            return render(request, 'index.html')
#退出业务流程处理
def logout(request):
    print('我的世界')
    # 删除当前登录者的session中的信息
    del request.session['number']
    del request.session['code']
    print('删除当前登录者的信息')
    # 重定向至登录页面
    return redirect('/login/')
#上传图片
def picupload(request):
    # 接收客户端请求数据
    obj = request.FILES.get('file', None)
    # 处理请求数据
    # 获取上传图片的信息
    picFilename = obj.name
    picFileSize = obj.size
    picFileStuff = os.path.splitext(picFilename)[1]
    # 测试
    print('\n上传文件信息：')
    print('‑' * 40)
    print('文件名称：{0}'.format(picFilename))
    print('文件大小：{0}'.format(picFileSize))
    print('文件后缀：{0}'.format(picFileStuff))
    # 创建可用文件类型列表
    allowedTypes = ['.png', '.jpg', '.gif', '.bmp', '.jpeg']
    # 判断上传文件类型是否受限
    if picFileStuff.lower() not in allowedTypes:
        print('文件类型不正确.')
        # 响应客户端
        return render(request, 'picupload.html', {'error_msg':'错误：文件类型不正确，请您选择一张图片上传!'})
    # 生成唯一的文件名称
    picUploadUniquecode = str(uuid.uuid1()) + picFileStuff
    print('上传文件唯一名称：{0}'.format(picUploadUniquecode))
    # 验证上传文件夹
    uploadDirPath = os.path.join(os.getcwd(), 'login/static/image')
    if not os.path.exists(uploadDirPath):
        # 创建文件夹
        os.mkdir(uploadDirPath)
        print('服务器上传文件夹创建完毕.')
    else:
        print('服务器上传文件夹已存在.')
    # 设置上传文件的全路径
    picFileFullPath = uploadDirPath + os.sep + picUploadUniquecode
    print('上传文件全路径：{0}'.format(picFileFullPath))
    # 二进制文件写入操作
    try:
        # 获取文件的关联并生成文件操作对象fp
        with open(picFileFullPath, 'wb+') as fp:
            # 分割上传文件（当上传文件大小2.5MB以上是自动分割）
            for chunk in obj.chunks():
                fp.write(chunk)
            print('[OK] 上传文件写入服务器.')
    except:
        print('[Error] 上传文件写入服务器失败.')
        # 响应客户端
        return render(request, 'picupload.html', {'error_msg':'[Error] 图片上传失败!'})
    # 响应客户端
    imgurl = '/static/image/' + picUploadUniquecode
    return HttpResponse(imgurl)

#用户注册信息存储到数据库 
def addDatails(request):
    if request.POST:
        # 接收客户端请求数据
        number = request.POST.get('number', None)
        code = request.POST.get('code', None)
        name = request.POST.get('name', None)
        head = request.POST.get('head', None)
        gender = request.POST.get('gender', None)
        city = request.POST.get('city', None)
        yx = request.POST.get('yx', None)
        signature = request.POST.get('signature', None)
        # 处理数据（添加数据表）
        PersonalDatails.objects.create(number = number, code = code,name=name,head=head,gender=gender,city=city,signature=signature,yx=yx)
        # 响应客户端
        return render(request, 'index.html')
    else:
        # 响应客户端（页面跳转）
        return render(request, 'register.html')
#读取数据库信息
def amend(request,id):
    em=PersonalDatails.objects.get(empno=id)
    return render(request,'amend.html',locals())
#读取用户修改信息并修改数据库信息
def qrxg(request):
    number = request.POST.get('number', None)
    code = request.POST.get('code', None)
    name = request.POST.get('name', None)
    head = request.POST.get('head', None)
    gender = request.POST.get('gender', None)
    city = request.POST.get('city', None)
    yx=request.POST.get('yx', None)
    signature = request.POST.get('signature', None)
    empno=request.POST.get('empno',None)
    PersonalDatails.objects.filter(empno=empno).update(number=number,code=code,name=name,head=head,gender=gender,city=city,signature=signature,yx=yx)
    return redirect("/login/index/")
#发送邮箱验证
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import random
#配置邮件发送基本格式

def fsxx(request,nun):
    global an
    from_addr="745908308@qq.com"
    to_addr=nun
    password="pppctqdyeytibfjf"
    #创建设置邮件消息对象
    am=[random.randint(0, 9) for i in range(6)]
    an=str(am[0])+str(am[1])+str(am[2])+str(am[3])+str(am[4])+str(am[5])
    message = MIMEText(an,'plain','utf-8')
    message["From"]=Header("博客验证","utf-8")
    message["To"]=Header("xll","utf-8")
    message["Subject"]=Header("python3测试","utf-8")
    #发送邮件
    try:
        server=smtplib.SMTP_SSL("smtp.qq.com",465)
        server.set_debuglevel(1)
        server.login(from_addr,password)
        server.sendmail(from_addr,[to_addr],message.as_string())
        flag=True
        print("邮件发送成功")
    except smtplib.SMTPException:
        flag=False
        print("邮件发送失败")
    finally:
        server.quit()
        return HttpResponse(flag)
#验证码验证
def yznr(request,nename):
        global an
        # 判断验证码是否正确
        flag=False
    
        if an==nename :
            flag = True
        print('唯一验证结果：{0}'.format(flag))
        # 响应客户端
        return HttpResponse(flag) 

def wzxx(request):
    title=request.POST.get('title',None)
    genre=request.POST.get('genre',None)
    artile=request.POST.get('artile',None)
    empno=request.POST.get('dept1',None)
    Content.objects.filter(empno=empno).update(title=title,genre=genre,artile=artile)
    return redirect('/login/ix/')
def wzxx1(request):
    title=request.POST.get('title',None)
    genre=request.POST.get('genre',None)
    artile=request.POST.get('artile',None)
    empno=request.POST.get('dept',None)
    dept=PersonalDatails.objects.get(name=empno)
    Content.objects.create(title=title,genre=genre,artile=artile,dept=dept)
    return redirect('/login/ix/')
#技术类显示
def jshu(request,id):
    # 获取session的数据
    number = request.session.get('number', None)
    if not number:
        # 跳转至登录
        return redirect('/login/index/')
    else:
        man=PersonalDatails.objects.get(number=number)
        a=man.number
        lstemp=Content.objects.filter(genre=id)

        # 创建分页器类并设置每页显示的数据格式
        paginator = Paginator(lstemp, 4) # 每页显示3条数据
        # 接收客户端传入的页码
        page = request.GET.get('page')
        # 根据用户传入的页码返回响应的页面数据集
        try:
            lstemp = paginator.page(page)
        except EmptyPage: # 首页查看处理
            lstemp = paginator.page(1)
        except PageNotAnInteger:
            lstemp = paginator.page(paginator.num_pages)
        # 请求转发跳转至home页面
        return render(request, 'ix.html',locals())



def jshu1(request,id):
    # 获取session的数据
    number = request.session.get('number', None)
    if not number:
        # 跳转至登录
        return redirect('/login/index/')
    else:
        man=PersonalDatails.objects.get(number=number)
        a=PersonalDatails.objects.get(number=number)
        lstemp=Content.objects.filter(dept=a.empno,genre=id)
        # lstemp=Content.objects.filter(genre=id)
        # 创建分页器类并设置每页显示的数据格式
        paginator = Paginator(lstemp, 3) # 每页显示3条数据
        # 接收客户端传入的页码
        page = request.GET.get('page')
        # 根据用户传入的页码返回响应的页面数据集
        try:
            lstemp = paginator.page(page)
        except EmptyPage: # 首页查看处理
            lstemp = paginator.page(1)
        except PageNotAnInteger:
            lstemp = paginator.page(paginator.num_pages)
        # 请求转发跳转至home页面
        return render(request, 'dengluzp1.html',locals())



def add(request):
    lstemp=Content.objects.all()
    # 创建分页器类并设置每页显示的数据格式
    paginator = Paginator(lstemp, 4) # 每页显示3条数据
    # 接收客户端传入的页码
    page = request.GET.get('page')

    # 根据用户传入的页码返回响应的页面数据集
    try:
        lstemp = paginator.page(page)
    except EmptyPage: # 首页查看处理
        lstemp = paginator.page(1)
    except PageNotAnInteger:
        lstemp = paginator.page(paginator.num_pages)
    # 请求转发跳转至home页面
    return render(request, 'dengluzq.html',locals())



def add1(request):
    number = request.session.get('number', None)
    man=PersonalDatails.objects.get(number=number)
    a=PersonalDatails.objects.get(number=number)
    lstemp=Content.objects.filter(dept=a.empno)
    # 创建分页器类并设置每页显示的数据格式
    paginator = Paginator(lstemp, 4) # 每页显示3条数据
    # 接收客户端传入的页码
    page = request.GET.get('page')
    # 根据用户传入的页码返回响应的页面数据集
    try:
        lstemp = paginator.page(page)
    except EmptyPage: # 首页查看处理
        lstemp = paginator.page(1)
    except PageNotAnInteger:
        lstemp = paginator.page(paginator.num_pages)
    # 请求转发跳转至home页面
    return render(request, 'dengluzp1.html',locals())

def amm(request,id):
    # 获取session的数据
    lstemp=Content.objects.filter(genre=id)
    # 创建分页器类并设置每页显示的数据格式
    paginator = Paginator(lstemp, 4) # 每页显示3条数据
    # 接收客户端传入的页码
    page = request.GET.get('page')
    # 根据用户传入的页码返回响应的页面数据集
    try:
        lstemp = paginator.page(page)
    except EmptyPage: # 首页查看处理
        lstemp = paginator.page(1)
    except PageNotAnInteger:
        lstemp = paginator.page(paginator.num_pages)
    # 请求转发跳转至home页面
    return render(request, 'dengluzq.html',locals())
def deleteContent(request, id):
    # 删除博客信息
    Content.objects.get(empno = id).delete()
    #删除博客评论内容
    Discuss.objects.filter(dept = id).delete()
    # 响应客户端
    return redirect('/login/an/')
    
def preUpdateContent(request,id):
    number = request.session.get('number', None)
    man=PersonalDatails.objects.get(number=number)
    # 获取指定id编号的博客信息
    ond = Content.objects.get(empno = id)
    # 响应客户端（跳转至updateEmp.html）
    return render(request, 'update.html',locals())


flag='1'
#验证码验证
def yznr1(request,nename):
    if request.POST:
        global an,flag
        # 判断验证码是否正确
        flag = True if an in nename else False
            # 响应客户端
        return HttpResponse(flag)
#密码判断，及跳转
def abcd(request):
    global an,flag
    yx=request.POST.get('yx',None)
    number=request.POST.get('number',None)
    yy=PersonalDatails.objects.get(number=number)
    if yx==yy.yx and flag=='1':
        return render(request,'xg.html',locals())
    else:
        return redirect('/login/xgmm1/')
def xgmm1(request):
    return render(request,'xgmm.html')
def wjmm(request):
    number=request.POST.get('number',None)
    code=request.POST.get('code',None)
    PersonalDatails.objects.filter(number = number).update(code=code)
    return redirect('/login/index/')

#读取博客内容
def abcde(request,id):
    number = request.session.get('number', None)
    man=PersonalDatails.objects.get(number=number)
    # 获取指定id编号的博客信息
    lstemp = Content.objects.get(empno = id)
    return render(request, 'abcde.html',locals())
#将评论内容存储到数据库，并实时显示评论内容
def abcdef(request):
    observer=request.POST.get('observer',None)
    print('就weakv呀额：',observer)
    comment=request.POST.get('comment',None)
    dept=request.POST.get('dept',None)
    Discuss.objects.create(observer=observer,comment=comment,dept=dept)
    ww=Discuss.objects.filter(dept=dept)
    number = request.session.get('number', None)
    man=PersonalDatails.objects.get(number=number)
    # 获取指定id编号的博客信息
    lstemp = Content.objects.get(empno = dept)
    # 响应客户端（跳转至updateEmp.html）
    return render(request, 'ckxx.html',locals())



# 将关注的人存储到数据库,name:关注的人的id
def abcdefg(request,na):
    number = request.session.get('number', None)
    man=PersonalDatails.objects.get(number=number)
    lstemp=Content.objects.all()
    paginator = Paginator(lstemp, 4) # 每页显示3条数据
    # 接收客户端传入的页码
    page = request.GET.get('page')
    # 根据用户传入的页码返回响应的页面数据集
    try:
        lstemp = paginator.page(page)
    except EmptyPage: # 首页查看处理
        lstemp = paginator.page(1)
    except PageNotAnInteger:
        lstemp = paginator.page(paginator.num_pages)
    # 请求转发跳转至home页面
    return render(request, 'ix.html',locals())
# 查看关注
def scbz(request):
    number = request.session.get('number', None)
    man=PersonalDatails.objects.get(number=number)
    abd=Attention.objects.filter(aa=man.empno)
    return render(request, 'gz.html',locals()) 
#删除关注
def scgz(request,id):
    Attention.objects.filter(pno=id).delete()
    return redirect('/login/gz/')
#主页搜索
an1=''
def ss(request):
    lst=[]
    global an1
    aa=request.POST.get('ss',None)
    if aa==None:
        aa=an1
    else:
        an1=aa
    for b in Content.objects.all():
        q=b.artile
        b=b.title
        c=b.find(aa)
        n=q.find(aa)
        lstemp=list(set(lst)) 
        if c>=0:
            e=Content.objects.filter(title=b)
            if e not in lstemp:
                lst.append(e)           
        if n>=0:
            w=Content.objects.filter(artile=q)
            if w not in lstemp:
                if c<0:
                    print('我的结果4555555',lst.count(w))
                    lst.append(w) 
    return render(request, 'ss.html',locals()) 

                
#搜索
an=''
def ss1(request):
    lst=[]
    global an
    number = request.session.get('number', None)
    man=PersonalDatails.objects.get(number=number)
    aa=request.POST.get('ss',None)
    if aa==None:
        aa=an
    else:
        an=aa
    for b in Content.objects.all():
        q=b.artile
        b=b.title
        c=b.find(aa)
        n=q.find(aa)
        lstemp=list(set(lst)) 
        if c>=0:
            e=Content.objects.filter(title=b)
            if e not in lstemp:
                lst.append(e)           
        if n>=0:
            w=Content.objects.filter(artile=q)
            if w not in lstemp:
                if c<0:
                    lst.append(w) 
    return render(request, 'ss1.html',locals()) 
#显示关注博主内容
def gzbz(request,id):
    number = request.session.get('number', None)
    man=PersonalDatails.objects.get(number=number)
    lstemp=Content.objects.filter(dept=id)
    paginator = Paginator(lstemp, 4) # 每页显示3条数据
    # 接收客户端传入的页码
    page = request.GET.get('page')
    # 根据用户传入的页码返回响应的页面数据集
    try:
        lstemp = paginator.page(page)
    except EmptyPage: # 首页查看处理
        lstemp = paginator.page(1)
    except PageNotAnInteger:
        lstemp = paginator.page(paginator.num_pages)
    # 请求转发跳转至home页面
    return render(request, 'gzbz.html',locals()) 

def xxqk5(request,id):
    lstemp=Content.objects.get(empno=id)
    number = request.session.get('number', None)
    man=PersonalDatails.objects.get(number=number)
    l=PersonalDatails.objects.get(empno=lstemp.dept.empno)
    abc=Attention.objects.filter(bb=lstemp.dept.empno)
    faage=False
    if abc.count() == 0:
        faage=True
    ww=Discuss.objects.filter(dept=lstemp.empno)

    return render(request, 'ckxx.html',locals())

def xxqk(request,id):
    lstemp=Content.objects.get(empno=id)
    number = request.session.get('number', None)
    man=PersonalDatails.objects.get(number=number)
    l=PersonalDatails.objects.get(empno=lstemp.dept.empno)
    abc=Attention.objects.filter(bb=lstemp.dept.empno)
    faage=False
    if abc.count() == 0:
        Attention.objects.create(nickname=l.name,aa=man.empno,bb=lstemp.dept.empno)
        faage=True
    ww=Discuss.objects.filter(dept=lstemp.empno)

    return render(request, 'ckxx.html',locals())
def xxqk1(request,id):
    lstemp=Content.objects.get(empno=id)
    ww=Discuss.objects.filter(dept=lstemp.empno)
    return render(request, 'ckxx1.html',locals())
def xxqk2(request,id):
    lstemp=Content.objects.get(empno=id)
    number = request.session.get('number', None)
    man=PersonalDatails.objects.get(number=number)
    ww=Discuss.objects.filter(dept=lstemp.empno)
    return render(request, 'ckxx2.html',locals())